<template>
  <el-dialog
    v-model="visible"
    :show-close="false"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    custom-class="command-panel-dialog"
    width="650px"
    top="15vh"
    @close="handleClose"
  >
    <div class="command-panel">
      <!-- 搜索框 -->
      <div class="search-box">
        <el-icon class="search-icon"><Search /></el-icon>
        <input
          ref="searchInputRef"
          v-model="searchKeyword"
          type="text"
          placeholder="搜索功能、快捷操作..."
          class="search-input"
          @input="handleSearch"
          @keydown="handleKeydown"
        />
        <div class="search-hint">
          <kbd>↑</kbd><kbd>↓</kbd> 导航 <kbd>Enter</kbd> 选择 <kbd>Esc</kbd> 关闭
        </div>
      </div>

      <!-- 结果列表 -->
      <div class="results-container" v-if="filteredResults.length > 0">
        <el-scrollbar max-height="400px">
          <!-- 分组显示 -->
          <div v-for="group in groupedResults" :key="group.type" class="result-group">
            <div class="group-title">{{ group.title }}</div>
            <div class="result-list">
              <div
                v-for="(item, index) in group.items"
                :key="item.id"
                class="result-item"
                :class="{ active: selectedIndex === getItemGlobalIndex(group.type, index) }"
                @click="handleSelect(item)"
                @mouseenter="selectedIndex = getItemGlobalIndex(group.type, index)"
              >
                <div class="item-icon" :style="{ background: item.color || '#409eff' }">
                  <el-icon :size="20"><component :is="item.icon" /></el-icon>
                </div>
                <div class="item-info">
                  <div class="item-title">
                    <span v-html="highlightKeyword(item.title)" />
                    <el-tag v-if="item.tag" size="small" :type="item.tagType">{{ item.tag }}</el-tag>
                  </div>
                  <div class="item-desc" v-if="item.description">{{ item.description }}</div>
                </div>
                <div class="item-extra" v-if="item.shortcut">
                  <kbd v-for="key in item.shortcut.split('+')" :key="key">{{ key }}</kbd>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-icon :size="64" color="#c0c4cc"><Search /></el-icon>
        <p>{{ searchKeyword ? '未找到相关结果' : '输入关键词搜索功能' }}</p>
      </div>

      <!-- 快捷提示 -->
      <div class="quick-tips" v-if="!searchKeyword">
        <div class="tip-title">快捷操作</div>
        <div class="tip-list">
          <div class="tip-item" v-for="tip in quickTips" :key="tip.key" @click="handleQuickAction(tip)">
            <el-icon><component :is="tip.icon" /></el-icon>
            <span>{{ tip.title }}</span>
            <kbd>{{ tip.key }}</kbd>
          </div>
        </div>
      </div>

      <!-- 最近使用 -->
      <div class="recent-section" v-if="!searchKeyword && recentCommands.length > 0">
        <div class="section-title">
          <el-icon><Clock /></el-icon>
          最近使用
        </div>
        <div class="recent-list">
          <div
            v-for="(item, index) in recentCommands"
            :key="item.id"
            class="recent-item"
            :class="{ active: selectedIndex === index }"
            @click="handleSelect(item)"
            @mouseenter="selectedIndex = index"
          >
            <div class="item-icon" :style="{ background: item.color || '#409eff' }">
              <el-icon :size="16"><component :is="item.icon" /></el-icon>
            </div>
            <span>{{ item.title }}</span>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useNavigationStore } from '@/stores/navigation'
import { useUserStore } from '@/stores/user'
import { useShortcutsStore } from '@/stores/shortcuts'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const navigationStore = useNavigationStore()
const shortcutsStore = useShortcutsStore()

// 初始化
onMounted(() => {
  shortcutsStore.init()
})

// 响应式数据
const searchInputRef = ref(null)
const searchKeyword = ref('')
const selectedIndex = ref(0)
const recentCommands = ref([])

// Props
const props = defineProps({
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue'])

// 可见性
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 所有命令数据
const allCommands = ref([
  // 快捷功能
  { id: 1, type: 'quick', title: '收银台', description: '快速销售结算', icon: 'ShoppingCart', path: '/sales/cashier', color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
  { id: 2, type: 'quick', title: '新建销售订单', description: '创建新的销售订单', icon: 'DocumentAdd', action: 'new-sales-order', color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)' },
  { id: 3, type: 'quick', title: '新建采购订单', description: '创建新的采购订单', icon: 'ShoppingBag', action: 'new-purchase-order', color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)' },
  { id: 4, type: 'quick', title: '商品入库', description: '快速商品入库', icon: 'Download', action: 'stock-in', color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)' },
  { id: 5, type: 'quick', title: '商品出库', description: '快速商品出库', icon: 'Upload', action: 'stock-out', color: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)' },
  
  // 导航菜单
  { id: 11, type: 'menu', title: '工作台', description: '返回工作台首页', icon: 'Monitor', path: '/', shortcut: 'Ctrl+H' },
  { id: 12, type: 'menu', title: '销售订单', description: '销售订单管理', icon: 'Document', path: '/sales/orders' },
  { id: 13, type: 'menu', title: '采购订单', description: '采购订单管理', icon: 'ShoppingBag', path: '/purchase/orders' },
  { id: 14, type: 'menu', title: '商品管理', description: '商品信息维护', icon: 'Box', path: '/inventory/products' },
  { id: 15, type: 'menu', title: '库存管理', description: '库存查询调整', icon: 'Coin', path: '/inventory/stock' },
  { id: 16, type: 'menu', title: '客户管理', description: '客户信息管理', icon: 'User', path: '/sales/customers' },
  { id: 17, type: 'menu', title: '供应商管理', description: '供应商信息管理', icon: 'OfficeBuilding', path: '/purchase/suppliers' },
  { id: 18, type: 'menu', title: '财务账户', description: '财务账户管理', icon: 'Money', path: '/finance/accounts' },
  { id: 19, type: 'menu', title: '数据报表', description: '数据分析报表', icon: 'DataAnalysis', path: '/reports/center' },
  { id: 20, type: 'menu', title: '系统设置', description: '系统配置设置', icon: 'Setting', path: '/system/settings' },
  
  // 系统操作
  { id: 31, type: 'action', title: '切换导航模式', description: '更改系统导航方式', icon: 'Menu', action: 'change-nav-mode', tag: '设置', tagType: 'info' },
  { id: 32, type: 'action', title: '切换主题', description: '明亮/暗黑主题切换', icon: 'Sunny', action: 'toggle-theme', shortcut: 'Ctrl+Shift+D' },
  { id: 33, type: 'action', title: '全屏模式', description: '进入/退出全屏', icon: 'FullScreen', action: 'toggle-fullscreen', shortcut: 'F11' },
  { id: 34, type: 'action', title: '退出登录', description: '退出当前账户', icon: 'SwitchButton', action: 'logout', tag: '账户', tagType: 'danger' },
  { id: 35, type: 'action', title: '清除缓存', description: '清除浏览器缓存', icon: 'Delete', action: 'clear-cache', tag: '系统', tagType: 'warning' },
  { id: 36, type: 'action', title: '数据导出', description: '导出当前页面数据', icon: 'Download', action: 'export-data', shortcut: 'Ctrl+E' },
  { id: 37, type: 'action', title: '打印页面', description: '打印当前页面', icon: 'Printer', action: 'print', shortcut: 'Ctrl+P' }
])

// 快捷提示
const quickTips = ref([
  { key: 'Ctrl+K', title: '命令面板', icon: 'Operation' },
  { key: 'Ctrl+/', title: '全局搜索', icon: 'Search' },
  { key: 'Ctrl+B', title: '切换侧边栏', icon: 'Fold' },
  { key: 'Ctrl+H', title: '返回首页', icon: 'HomeFilled' }
])

// 自定义快捷方式命令
const customShortcutCommands = computed(() => {
  return shortcutsStore.allShortcuts.map(shortcut => ({
    id: 'shortcut-' + shortcut.path,
    type: 'quick',
    title: shortcut.name,
    description: shortcut.description || '快速访问 ' + shortcut.path,
    icon: shortcut.icon || 'HomeFilled',
    action: 'navigate',
    path: shortcut.path,
    tag: '快捷方式',
    tagType: 'success'
  }))
})

// 合并所有命令
const allCommandsWithShortcuts = computed(() => {
  return [...allCommands.value, ...customShortcutCommands.value]
})

// 过滤结果
const filteredResults = computed(() => {
  if (!searchKeyword.value) return []
  
  const keyword = searchKeyword.value.toLowerCase()
  return allCommandsWithShortcuts.value.filter(item => {
    return item.title.toLowerCase().includes(keyword) ||
           item.description?.toLowerCase().includes(keyword) ||
           item.tag?.toLowerCase().includes(keyword)
  })
})

// 分组结果
const groupedResults = computed(() => {
  const groups = {
    quick: { type: 'quick', title: '⚡ 快捷功能', items: [] },
    menu: { type: 'menu', title: '📋 菜单导航', items: [] },
    action: { type: 'action', title: '⚙️ 系统操作', items: [] }
  }
  
  filteredResults.value.forEach(item => {
    if (groups[item.type]) {
      groups[item.type].items.push(item)
    }
  })
  
  return Object.values(groups).filter(group => group.items.length > 0)
})

// 获取项目的全局索引
const getItemGlobalIndex = (groupType, itemIndex) => {
  let globalIndex = 0
  for (const group of groupedResults.value) {
    if (group.type === groupType) {
      return globalIndex + itemIndex
    }
    globalIndex += group.items.length
  }
  return 0
}

// 高亮关键词
const highlightKeyword = (text) => {
  if (!searchKeyword.value) return text
  const regex = new RegExp(`(${searchKeyword.value})`, 'gi')
  return text.replace(regex, '<span class="highlight">$1</span>')
}

// 方法
const handleSearch = () => {
  selectedIndex.value = 0
}

const handleKeydown = (e) => {
  const totalItems = filteredResults.value.length || recentCommands.value.length
  
  if (e.key === 'ArrowDown') {
    e.preventDefault()
    selectedIndex.value = (selectedIndex.value + 1) % totalItems
  } else if (e.key === 'ArrowUp') {
    e.preventDefault()
    selectedIndex.value = (selectedIndex.value - 1 + totalItems) % totalItems
  } else if (e.key === 'Enter') {
    e.preventDefault()
    const item = searchKeyword.value 
      ? filteredResults.value[selectedIndex.value]
      : recentCommands.value[selectedIndex.value]
    if (item) {
      handleSelect(item)
    }
  }
}

const handleSelect = (item) => {
  // 添加到最近使用
  addToRecent(item)
  
  if (item.path) {
    router.push(item.path)
    visible.value = false
  } else if (item.action) {
    executeAction(item.action)
    visible.value = false
  }
}

const handleQuickAction = (tip) => {
  ElMessage.info(`执行快捷操作: ${tip.title}`)
}

const executeAction = (action) => {
  switch (action) {
    case 'new-sales-order':
      router.push('/sales/orders')
      ElMessage.success('打开新建销售订单')
      break
    case 'new-purchase-order':
      router.push('/purchase/orders')
      ElMessage.success('打开新建采购订单')
      break
    case 'stock-in':
      ElMessage.success('打开商品入库')
      break
    case 'stock-out':
      ElMessage.success('打开商品出库')
      break
    case 'change-nav-mode':
      window.dispatchEvent(new CustomEvent('show-navigation-settings'))
      break
    case 'toggle-theme':
      const darkMode = !navigationStore.settings.darkMode
      navigationStore.updateSettings({ darkMode })
      ElMessage.success(darkMode ? '已切换到暗黑模式' : '已切换到明亮模式')
      break
    case 'toggle-fullscreen':
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen()
      } else {
        document.exitFullscreen()
      }
      break
    case 'logout':
      visible.value = false
      ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const userStore = useUserStore()
        userStore.logout()
        router.push('/login')
        ElMessage.success('已退出登录')
      }).catch(() => {})
      break
    case 'clear-cache':
      localStorage.clear()
      ElMessage.success('缓存已清除')
      break
    case 'export-data':
      ElMessage.success('开始导出数据')
      break
    case 'print':
      window.print()
      break
    default:
      ElMessage.info(`执行操作: ${action}`)
  }
}

const addToRecent = (item) => {
  const exists = recentCommands.value.find(cmd => cmd.id === item.id)
  if (!exists) {
    recentCommands.value.unshift(item)
    if (recentCommands.value.length > 5) {
      recentCommands.value.pop()
    }
    // 保存到本地
    localStorage.setItem('recent-commands', JSON.stringify(recentCommands.value))
  }
}

const handleClose = () => {
  searchKeyword.value = ''
  selectedIndex.value = 0
}

// 监听对话框打开
watch(visible, async (val) => {
  if (val) {
    await nextTick()
    searchInputRef.value?.focus()
    
    // 加载最近使用
    const saved = localStorage.getItem('recent-commands')
    if (saved) {
      try {
        recentCommands.value = JSON.parse(saved)
      } catch (error) {
        console.error('Failed to load recent commands:', error)
      }
    }
  }
})

// 监听store的命令面板状态
watch(() => navigationStore.commandPanelVisible, (val) => {
  visible.value = val
})

watch(visible, (val) => {
  if (val !== navigationStore.commandPanelVisible) {
    navigationStore.toggleCommandPanel()
  }
})
</script>

<style>
.command-panel-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.command-panel-dialog .el-dialog__header {
  display: none;
}

.command-panel-dialog .el-dialog__body {
  padding: 0;
}
</style>

<style scoped>
.command-panel {
  background: #fff;
}

.search-box {
  position: relative;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.search-icon {
  position: absolute;
  left: 30px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 20px;
  color: #909399;
}

.search-input {
  width: 100%;
  height: 48px;
  padding: 0 120px 0 48px;
  border: none;
  outline: none;
  font-size: 16px;
  color: #303133;
  background: transparent;
}

.search-input::placeholder {
  color: #c0c4cc;
}

.search-hint {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  gap: 8px;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.search-hint kbd {
  padding: 2px 6px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 11px;
  font-family: monospace;
}

.results-container {
  padding: 12px 0;
}

.result-group {
  margin-bottom: 16px;
}

.group-title {
  padding: 8px 20px;
  font-size: 13px;
  font-weight: 600;
  color: #909399;
}

.result-list {
  padding: 0 12px;
}

.result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.result-item:hover,
.result-item.active {
  background: #f5f7fa;
}

.item-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 2px;
}

.item-title :deep(.highlight) {
  color: #409eff;
  background: #ecf5ff;
  padding: 0 2px;
  border-radius: 2px;
}

.item-desc {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-extra {
  display: flex;
  gap: 4px;
}

.item-extra kbd {
  padding: 2px 6px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 11px;
  font-family: monospace;
  color: #606266;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.empty-state p {
  margin: 16px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.quick-tips {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
}

.tip-title {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 12px;
}

.tip-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 13px;
  color: #606266;
}

.tip-item:hover {
  background: #e4e7ed;
}

.tip-item span {
  flex: 1;
}

.tip-item kbd {
  padding: 2px 6px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 11px;
  font-family: monospace;
}

.recent-section {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 12px;
}

.recent-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 13px;
  color: #606266;
}

.recent-item:hover,
.recent-item.active {
  background: #e4e7ed;
}

.recent-item .item-icon {
  width: 24px;
  height: 24px;
}

/* 暗黑模式 */
.dark .command-panel {
  background: #1f1f1f;
  color: #e4e7ed;
}

.dark .search-box {
  border-bottom-color: #3a3a3a;
}

.dark .search-input {
  color: #e4e7ed;
}

.dark .result-item:hover,
.dark .result-item.active {
  background: #2a2a2a;
}

.dark .item-title {
  color: #e4e7ed;
}

.dark .quick-tips,
.dark .recent-section {
  border-top-color: #3a3a3a;
}

.dark .tip-item,
.dark .recent-item {
  background: #2a2a2a;
  color: #e4e7ed;
}

.dark .tip-item:hover,
.dark .recent-item:hover,
.dark .recent-item.active {
  background: #3a3a3a;
}
</style>
